//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import { makeAutoObservable, runInAction } from 'mobx';
import type { ServerInfo } from "@/api/project_server";
import { get_server, gen_access_token } from "@/api/project_server";
import { get_session } from '@/api/user';
import { request } from '@/utils/request';
import type { MemberPerm } from '@/api/dragonfly/member';
import { get_my_perm } from '@/api/dragonfly/member';
import type { ServiceInfo, SORT_BY } from "@/api/dragonfly/trace";

export interface TraceTimeFilter {
    pastHour: number; //过去几个小时至今的trace
    rootSpanName: string; //空字符串标识不使用rootSpanName
    sortBy: SORT_BY;
}

export interface TraceFilter {
    serviceInfo: ServiceInfo;
    filterByTraceId: boolean;
    traceId?: string;
    timeFilter?: TraceTimeFilter;
}

export class AppStore {
    constructor() {
        makeAutoObservable(this);
    }

    private _adminUser = false;
    private _projectId = "";
    private _remoteServer: ServerInfo | null = null;
    private _myPerm: MemberPerm | null = null;

    get adminUser() {
        return this._adminUser;
    }

    get projectId() {
        return this._projectId;
    }

    get remoteServer() {
        return this._remoteServer;
    }

    get myPerm() {
        return this._myPerm;
    }

    async loadMyPerm() {
        if (this._remoteServer == null) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: this._projectId,
            server_id: this._remoteServer.server_id,
        }));
        const permRes = await request(get_my_perm(this._remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: this._remoteServer.server_id,
        }))
        runInAction(() => {
            this._myPerm = permRes.perm;
        });
    }

    async init(projectId: string, remoteId: string, adminUser: boolean) {
        const sessionId = await get_session();
        const res = await request(get_server({
            session_id: sessionId,
            project_id: projectId,
            server_id: remoteId,
        }));
        runInAction(() => {
            this._adminUser = adminUser;
            this._projectId = projectId;
            this._remoteServer = res.server_info;
        });
        await this.loadMyPerm();
    }

    private _traceFilter: TraceFilter | null = null;

    get traceFilter() {
        return this._traceFilter
    }

    set traceFilter(val: TraceFilter | null) {
        runInAction(() => {
            this._traceFilter = val;
        })
    }
}